#include "Session.h"

#include <QSqlQuery>
#include <As/Logic/ControlLogic.h>
#include <As/Utils/Md5.h>

namespace As {

Session::Session(const QString & sid, QObject *parent) :
    AbstractHttpLogic(parent),
    m_authorized(false),
    m_sid(sid)
{
    connect(&m_timer, SIGNAL(timeout()), this, SLOT(expiry()));
    m_timer.setSingleShot(true);
    m_timer.setInterval(2000);
    m_timer.start();
}

void Session::request(HttpRequest req) {
    QString action = req.m_headerMap["action"];
    QString param = req.m_headerMap["param"];
    QString login = req.m_headerMap["login"];
    QString sessionId = req.m_headerMap["session-id"];
    if (sessionId.isEmpty() || action.isEmpty() || login.isEmpty()) {
        emit response(HttpResponse(req.m_socket, "", "400 Bad Request"));
    }
    if (action == "hello") {
        m_login = login;
        m_passKey = QString().setNum(qrand(), 16);
        HttpResponse resp(req.m_socket);
        resp.addHeader("action", "hello_conf");
        resp.addHeader("param", m_passKey);
        emit response(resp);
    }
    if (action == "auth") {
        if (checkPass(login, param)) {
            m_authorized = true;
            HttpResponse resp(req.m_socket);
            resp.addHeader("action", "auth_conf");
            emit response(resp);
        }
        else {
            HttpResponse resp(req.m_socket, "", "401 Unauthorized");
            resp.addHeader("action", "auth_rej");
            emit response(resp);
        }
    }
    if (action == "alive") {
        if (check(login)) {
            HttpResponse resp(req.m_socket);
            resp.addHeader("action", "alive_conf");
            emit response(resp);
        }
        else {
            HttpResponse resp(req.m_socket, "", "401 Unauthorized");
            resp.addHeader("action", "alive_rej");
            emit response(resp);
        }
    }
}

bool Session::checkPass(const QString &login, const QString &pass) {
    if (login == m_login) {
        QSqlQuery query("SELECT password FROM accounts WHERE login = \"" + login + "\"");
        if (query.next()) {
            QString db_pass = query.value(0).toString();
            qDebug() << db_pass << m_passKey << pass;
            if (pass == MD5().update(db_pass + m_passKey).final()) {
                return true;
            }
        }
    }
    return false;
}

bool Session::check(const QString & login) {
    if ((login == m_login) && (m_authorized)) {
        m_timer.stop();
        m_timer.setInterval(10000);
        m_timer.start();
        return true;
    }
    else {
        return false;
    }
}

void Session::expiry() {
    m_authorized = false;
    qDebug() << "session inactive timeout expiry";
    ((ControlLogic *)parent())->deleteSession(m_sid);
}

}
